/**
 * 用以封装上传图片文件
 */
const multer=require("multer");
const path=require("path");
const mime=require("mime");

// const upload=multer({
//     dest:path.join(__dirname,"../public/uploads")
// });

const storage=multer.diskStorage({
    destination:function(req,file,cb){
        cb(null,path.join(__dirname,"../public/uploads"));
    },
    filename:function(req,file,cb){
        let extName=mime.getExtension(file.mimetype);
        let MyDate=new Date();
        let Year=MyDate.getFullYear(); //获取年
        let Month=MyDate.getMonth()+1<10?"0"+(MyDate.getMonth()+1):MyDate.getMonth()+1; //获取月
        let Day=MyDate.getDate()<10?"0"+MyDate.getDate():MyDate.getDate(); //获取日
        let Hour=MyDate.getHours()<10?"0"+MyDate.getHours():MyDate.getHours(); //获取小时
        let Minute=MyDate.getMinutes()<10?"0"+MyDate.getMinutes():MyDate.getMinutes(); //获取分钟
        let Second=MyDate.getSeconds()<10?"0"+MyDate.getSeconds():MyDate.getSeconds(); //获取秒钟
        let formatDate=Year+Month+Day+Hour+Minute+Second+"";
        let fileName=file.fieldname+"_"+formatDate+"."+extName;
        cb(null,fileName);
    }
});

const limits={
    fileSize:20*1000*1000,
    files:1
};

function fileFilter(req,file,cb){
    const acceptType=[
        "image/png",
        "image/jpg",
        "image/jpeg",
        "image/gif"
    ];
    if(!acceptType.includes(file.mimetype)){
        cb(new Error("文件类型必须是图片类型"));
    }else{ //上传的图片符合类型时做通过处理
        cb(null,true);
    };
};

const upload=multer({
    storage,
    limits,
    fileFilter
});



module.exports=upload;